package com.ustc.hewei.detectbeats.net;

import com.alibaba.fastjson2.JSON;
import com.ustc.hewei.detectbeats.detect.SendBeat;
import com.ustc.hewei.rpc.common.Utils.MessageSerialize;
import com.ustc.hewei.rpc.common.protocol.NotifyType;
import com.ustc.hewei.rpc.common.protocol.NotifyMessage;
import com.ustc.hewei.rpc.common.protocol.Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
* @description: 对服务端发来的信息进行处理，存入缓存
* @author hewei
* @date 2022/8/17 20:05
* @version 1.0
*/

@Slf4j
public class NotifyHandler {
    private final ConcurrentHashMap<String, List<String>> serviceMap;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final SendBeat sendBeat;

    public NotifyHandler(ConcurrentHashMap<String, List<String>> serviceMap, SendBeat sendBeat) {
        this.serviceMap = serviceMap;
        this.sendBeat = sendBeat;
    }

    /*
     * @description: 对于服务注册的通知信息进行处理，并返回处理成功与否的信息
     * @param data 服务端发来的通知信息
     * @return byte[] 返回的处理结果
     * @author: hewei
     * @date: 2022/8/19 21:21
     **/
    public byte[] handler(byte[] data) {
        NotifyMessage notifyMessage = MessageSerialize.byteArrayToNotify(data);
        if (notifyMessage.getStatus() == NotifyType.UPDATE) {
            String key = notifyMessage.getKey();
            Service service = notifyMessage.getService();
            String jsonString = JSON.toJSONString(service);
            stringRedisTemplate.opsForSet().remove(key, jsonString);
            sendBeat.getInvalidIpCount().put(service.getAddress(), sendBeat.getInvalidIpCount().getOrDefault(service.getAddress(), 0) + 1);
            log.info("收到客户端更新通知，已更新 {} 状态", service.getAddress());
        } else {
            Service service = notifyMessage.getService();
            String key = notifyMessage.getKey();
            String address = service.getAddress();
            if (!serviceMap.containsKey(address)) serviceMap.put(address, new ArrayList<>());
            serviceMap.get(address).add(key);
            log.info("注册中心存入{},缓存成功", notifyMessage.getService());
        }
        NotifyMessage res = new NotifyMessage();
        res.setStatus(NotifyType.SUCCESS);
        return MessageSerialize.objectToByteArray(res);
    }
}
